﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Prism.Commands;
using Prism.Mvvm;
using CPlatePrintSys.Domain.Models;
using CPlatePrintSys.Domain.Services;
using CPlatePrintSys.Win.Views;
using System.Windows;
using CPlatePrintSys.Application.ViewModels;
using Newtonsoft.Json;
using CPlatePrintSys.Infrastructure.Repositories;

namespace CPlatePrintSys.Win.ViewModels
{
    public class ExportDocumentsViewModel : BindableBase
    {
        private readonly IGlobalConfigService _globalConfigService;
        private readonly List<PlateAnnotationInfoViewModel> _selectedItems;
        private readonly IPlateAnnotationInfoRepository _plateAnnotationRepository;

        public ExportDocumentsViewModel(IGlobalConfigService globalConfigService, List<PlateAnnotationInfoViewModel> selectedItems, IPlateAnnotationInfoRepository plateAnnotationRepository = null)
        {
            _globalConfigService = globalConfigService;
            _selectedItems = selectedItems ?? new List<PlateAnnotationInfoViewModel>();
            _plateAnnotationRepository = plateAnnotationRepository;

            InitializeCommands();
            InitializeExportProcess();
        }

        #region Properties

        private string _title = "提示";
        public string Title
        {
            get => _title;
            set => SetProperty(ref _title, value);
        }

        private bool _isFailed = false;
        public bool IsFailed
        {
            get => _isFailed;
            set => SetProperty(ref _isFailed, value);
        }

        private string _message = "";
        public string Message
        {
            get => _message;
            set => SetProperty(ref _message, value);
        }

        private bool _isExporting = false;
        public bool IsExporting
        {
            get => _isExporting;
            set => SetProperty(ref _isExporting, value);
        }

        private int _currentProgress = 0;
        public int CurrentProgress
        {
            get => _currentProgress;
            set => SetProperty(ref _currentProgress, value);
        }

        private int _totalCount = 0;
        public int TotalCount
        {
            get => _totalCount;
            set => SetProperty(ref _totalCount, value);
        }

        private string _currentFileName = "";
        public string CurrentFileName
        {
            get => _currentFileName;
            set => SetProperty(ref _currentFileName, value);
        }

        private bool _canConfirm = false;
        public bool CanConfirm
        {
            get => _canConfirm;
            set => SetProperty(ref _canConfirm, value);
        }

        #endregion

        #region Commands

        public ICommand ConfirmCommand { get; private set; }
        public ICommand CancelCommand { get; private set; }

        private void InitializeCommands()
        {
            ConfirmCommand = new DelegateCommand(ExecuteConfirm, () => CanConfirm);
            CancelCommand = new DelegateCommand(ExecuteCancel);
        }

        private void ExecuteConfirm()
        {
            if (IsFailed)
            {
                // 如果失败，重新尝试
                InitializeExportProcess();
            }
            else
            {
                // 成功完成，关闭窗口并返回true
                CloseWindow(true);
            }
        }

        private void ExecuteCancel()
        {
            CloseWindow(false);
        }

        private void CloseWindow(bool? dialogResult = null)
        {
            // 查找并关闭当前窗口
            var currentWindow = App.Current.Windows.OfType<ExportDocumentsView>().FirstOrDefault();
            if (currentWindow != null)
            {
                if (dialogResult.HasValue)
                {
                    currentWindow.DialogResult = dialogResult.Value;
                }
                currentWindow.Close();
            }
        }

        #endregion

        #region Export Process

        private async void InitializeExportProcess()
        {
            try
            {
                // 过滤已标注完成的图纸
                var completedItems = _selectedItems.Where(x => x.IsAnnotationGenerated).ToList();
                
                if (!completedItems.Any())
                {
                    IsFailed = true;
                    Message = "没有找到已标注完成的图纸，无法输出。";
                    CanConfirm = true;
                    return;
                }

                TotalCount = completedItems.Count;
                CurrentProgress = 0;
                IsExporting = true;
                IsFailed = false;
                CanConfirm = false;

                // 获取输出目录配置
                var outputPath = await _globalConfigService.GetOutputDirectoryPathAsync();
                if (string.IsNullOrEmpty(outputPath))
                {
                    throw new InvalidOperationException("未配置输出目录，请在全局配置中设置输出目录。");
                }

                // 确保输出目录存在
                if (!Directory.Exists(outputPath))
                {
                    Directory.CreateDirectory(outputPath);
                }

                // 开始导出过程
                await ExportDocumentsAsync(completedItems, outputPath);

                // 导出完成
                IsExporting = false;
                Message = "输出完成";
                CanConfirm = true;

                // 确保命令状态更新
                ((DelegateCommand)ConfirmCommand).RaiseCanExecuteChanged();
            }
            catch (Exception ex)
            {
                IsExporting = false;
                IsFailed = true;
                Message = $"输出出错: {ex.Message}\n请检查网络环境后再重试。";
                CanConfirm = true;
            }
        }

        private async Task ExportDocumentsAsync(List<PlateAnnotationInfoViewModel> items, string outputPath)
        {
            var appDirectory = AppDomain.CurrentDomain.BaseDirectory;
            var tmpDataPath = Path.Combine(appDirectory, "temp");

            if (!Directory.Exists(tmpDataPath))
            {
                throw new DirectoryNotFoundException($"临时目录不存在: {tmpDataPath}");
            }

            for (int i = 0; i < items.Count; i++)
            {
                var item = items[i];
                CurrentProgress = i + 1;
                CurrentFileName = item.SheetConsistentNo;

                try
                {
                    // 根据布局类型处理不同的文件
                    if (item.LayoutMean == LayoutMean.MirrorLayout)
                    {
                        // 镜像布局：需要复制两个文件
                        await CopyMirrorLayoutFiles(item, tmpDataPath, outputPath);
                    }
                    else if (item.LayoutMean == LayoutMean.MergedLayout)
                    {
                        // 合并布局：复制合并后的文件
                        await CopyMergedLayoutFile(item, tmpDataPath, outputPath);
                    }
                    else
                    {
                        // 其他布局：复制单个文件
                        await CopySingleFile(item, tmpDataPath, outputPath);
                    }

                    // 更新进度信息
                    Message = $"正在输出第{CurrentProgress}张图纸,总共{TotalCount}张图纸......";
                }
                catch (Exception ex)
                {
                    throw new Exception($"输出图纸 {item.SheetConsistentNo} 时发生错误: {ex.Message}");
                }

                // 添加小延迟，让UI能够更新
                await Task.Delay(100);
            }
        }

        private async Task CopyMirrorLayoutFiles(PlateAnnotationInfoViewModel item, string tmpDataPath, string outputPath)
        {
            var sheetNo = item.SheetConsistentNo;
            var copiedFiles = new List<string>();
            
            // 复制原始文件
            var originalFileName = $"{sheetNo}.dxf";
            var originalTmpPath = Path.Combine(tmpDataPath, originalFileName);
            var originalOutputPath = Path.Combine(outputPath, originalFileName);
            
            if (File.Exists(originalTmpPath))
            {
                await CopyFileAsync(originalTmpPath, originalOutputPath);
                copiedFiles.Add(originalFileName);
                System.Diagnostics.Debug.WriteLine($"已复制镜像布局原始文件: {originalFileName}");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine($"镜像布局原始文件不存在: {originalTmpPath}");
            }

            // 复制镜像文件
            var mirrorFileName = $"{sheetNo}_Mirrored.dxf";
            var mirrorTmpPath = Path.Combine(tmpDataPath, mirrorFileName);
            var mirrorOutputPath = Path.Combine(outputPath, mirrorFileName);
            
            if (File.Exists(mirrorTmpPath))
            {
                await CopyFileAsync(mirrorTmpPath, mirrorOutputPath);
                copiedFiles.Add(mirrorFileName);
                System.Diagnostics.Debug.WriteLine($"已复制镜像布局镜像文件: {mirrorFileName}");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine($"镜像布局镜像文件不存在: {mirrorTmpPath}");
            }

            if (copiedFiles.Count == 0)
            {
                throw new FileNotFoundException($"镜像布局 {sheetNo} 的临时文件不存在，无法输出");
            }

            // 设置标注图纸路径（使用原始文件路径）
            await SetAnnotationDrawingPathAsync(item, originalOutputPath);

            System.Diagnostics.Debug.WriteLine($"镜像布局 {sheetNo} 输出完成，共复制 {copiedFiles.Count} 个文件");
        }

        private async Task CopyMergedLayoutFile(PlateAnnotationInfoViewModel item, string tmpDataPath, string outputPath)
        {
            var sheetNo = item.SheetConsistentNo;
            var fileName = $"{sheetNo}.dxf";
            var tmpPath = Path.Combine(tmpDataPath, fileName);
            var outputFilePath = Path.Combine(outputPath, fileName);
            
            if (File.Exists(tmpPath))
            {
                await CopyFileAsync(tmpPath, outputFilePath);
                System.Diagnostics.Debug.WriteLine($"已复制合并布局文件: {fileName}");
                
                // 设置标注图纸路径
                await SetAnnotationDrawingPathAsync(item, outputFilePath);
            }
            else
            {
                throw new FileNotFoundException($"合并布局 {sheetNo} 的临时文件不存在: {tmpPath}");
            }

            System.Diagnostics.Debug.WriteLine($"合并布局 {sheetNo} 输出完成");
        }

        private async Task CopySingleFile(PlateAnnotationInfoViewModel item, string tmpDataPath, string outputPath)
        {
            var sheetNo = item.SheetConsistentNo;
            var fileName = $"{sheetNo}.dxf";
            var tmpPath = Path.Combine(tmpDataPath, fileName);
            var outputFilePath = Path.Combine(outputPath, fileName);
            
            if (File.Exists(tmpPath))
            {
                await CopyFileAsync(tmpPath, outputFilePath);
                System.Diagnostics.Debug.WriteLine($"已复制单个文件: {fileName}");
                
                // 设置标注图纸路径
                await SetAnnotationDrawingPathAsync(item, outputFilePath);
            }
            else
            {
                throw new FileNotFoundException($"单个文件 {sheetNo} 的临时文件不存在: {tmpPath}");
            }

            System.Diagnostics.Debug.WriteLine($"单个文件 {sheetNo} 输出完成");
        }

        private async Task CopyFileAsync(string sourcePath, string destinationPath)
        {
            try
            {
                // 确保目标目录存在
                var destinationDir = Path.GetDirectoryName(destinationPath);
                if (!Directory.Exists(destinationDir))
                {
                    Directory.CreateDirectory(destinationDir);
                }

                // 如果目标文件已存在，先删除
                if (File.Exists(destinationPath))
                {
                    File.Delete(destinationPath);
                }

                // 复制文件
                using (var sourceStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (var destinationStream = new FileStream(destinationPath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    await sourceStream.CopyToAsync(destinationStream);
                }

                System.Diagnostics.Debug.WriteLine($"文件复制成功: {sourcePath} -> {destinationPath}");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"文件复制失败: {sourcePath} -> {destinationPath}, 错误: {ex.Message}");
                throw new Exception($"复制文件失败 {Path.GetFileName(sourcePath)}: {ex.Message}");
            }
        }

        /// <summary>
        /// 设置标注图纸路径到数据库
        /// </summary>
        private async Task SetAnnotationDrawingPathAsync(PlateAnnotationInfoViewModel item, string annotationPath)
        {
            try
            {
                if (_plateAnnotationRepository != null)
                {
                    // 更新数据库中的标注图纸路径
                    await _plateAnnotationRepository.UpdateAnnotationDrawingPathAsync(item.Id, annotationPath);
                    
                    // 更新内存中的对象
                    item.OriginalData.AnnotationDrawingPath = annotationPath;
                    
                    // 触发属性更新通知，让UI知道数据已更改
                    item.RefreshProperty(nameof(item.AnnotationDrawingPath));
                    
                    System.Diagnostics.Debug.WriteLine($"已设置标注图纸路径: {item.SheetConsistentNo} -> {annotationPath}");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"Repository为空，无法更新标注图纸路径: {item.SheetConsistentNo}");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"设置标注图纸路径失败: {ex.Message}");
                // 不抛出异常，避免影响导出流程
            }
        }

        #endregion
    }
}
